import { login, logout } from '@/api/user'
import { getAdminInfo, getToken, removeToken, setAdminInfo, setIsShopManage, setToken } from '@/utils/auth'
import router, { getAsyncMenus, resetRouter } from '@/router'
import Cookies from 'js-cookie'

const state = {
  token: getToken(),
  name: Cookies.get('realName'),
  adminInfo: getAdminInfo,
  avatar: '',
  introduction: '',
  roles: [],
  apis: [],
  menus: [],
  childrenShopList: [],
  isShopManage: false
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_IS_SHOP_MANAGE: (state, isShopManage) => {
    state.isShopManage = isShopManage
    setIsShopManage(isShopManage)
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
    Cookies.set('realName', name)
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_APIS: (state, apis) => {
    state.apis = apis
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_CHILDREN_SHOP_LIST: (state, shopList) => {
    state.childrenShopList = shopList || []
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, type } = userInfo
    return new Promise((resolve, reject) => {
      login({ name: username.trim(), password: password, type: type }).then(response => {
        const { data, code } = response
        if (code != '200') {
          reject('')
          return
        }
        commit('SET_TOKEN', data.token)
        commit('SET_NAME', data.realName)
        Cookies.set('isShopManage', false)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  getMenus({ commit }) {
    return new Promise((resolve, reject) => {
      getAsyncMenus().then((res) => {
        commit('SET_MENUS', res.menus)
        commit('SET_APIS', res.apis)
        resolve(res.menus)
      })
    })
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      const data = {
        roles: ['admin'],
        name: 'vue',
        avatar: '',
        introduction: 'vue-element-admin'
      }

      const { roles, name, avatar, introduction } = data

      // roles must be a non-empty array
      if (!roles || roles.length <= 0) {
        reject('getInfo: roles must be a non-null array!')
      }

      // commit('SET_ROLES', roles)
      // commit('SET_NAME', name)
      // commit('SET_AVATAR', avatar)
      // commit('SET_INTRODUCTION', introduction)
      resolve(data)

      // getInfo(state.token).then(response => {
      //   const { data } = response
      //
      //   if (!data) {
      //     reject('Verification failed, please Login again.')
      //   }
      //
      //   const { roles, name, avatar, introduction } = data
      //
      //   // roles must be a non-empty array
      //   if (!roles || roles.length <= 0) {
      //     reject('getInfo: roles must be a non-null array!')
      //   }
      //
      //   commit('SET_ROLES', roles)
      //   commit('SET_NAME', name)
      //   commit('SET_AVATAR', avatar)
      //   commit('SET_INTRODUCTION', introduction)
      //   resolve(data)
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_MENUS', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
